package com.winnie.controller;

import com.winnie.bean.ResponseEntity;
import com.winnie.bean.UserEntity;
import com.winnie.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 查询用户并返回
     *
     * @param username
     * @return
     */
    @RequiresPermissions({"/user/getUser"})
    @GetMapping("/getUser")
    @ResponseBody
    public UserEntity getUser(String username) {
        UserEntity userEntity = userService.getUser(username);
        return userEntity;
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("username")String username,
                        @RequestParam("password")String password
    ) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return e.toString();
        }
        UserEntity user = userService.findUser(username, password);
        // 缓存用户信息
        Session session = subject.getSession(true);
        session.setAttribute("user", user);
        // 缓存角色
        Set<String> roleList = userService.findRole(username);
        session.setAttribute("role", roleList);
        // 缓存权限
        Set<String> permissionList = userService.findPermission(username);
        session.setAttribute("permission", permissionList);

        return "login successfully";
    }

    @RequiresRoles("admin")
    @PostMapping("/add")
    public ResponseEntity addUser(@RequestParam("username") String username,
                              @RequestParam("password") String password
    ){
        userService.addUser(username,password);
        return ResponseEntity.success("添加成功");
    }
}
